import React, {
  memo,
  useRef,
  useState,
  forwardRef,
  useImperativeHandle,
  Ref,
  useEffect,
  useCallback
} from "react";
import { shallowEqual, useSelector, useDispatch } from 'react-redux'
import { message, Modal, Checkbox } from "antd";
import HYFormCom from "components/form";
import CheckBoxAll from 'components/checkboxAll';
import { validateEmail, validatePhone } from "utils/validate.js";
import { custom } from "services/common";
// import CryptoJs from "crypto-js";
import { GetRole } from "services/permission";
import { CheckboxValueType } from "_antd@4.14.0@antd/lib/checkbox/Group";
import { setRoleMenu } from './store'

declare module 'react' { //给div上增加自定义属性  相当于h货站
  interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> {
    // extends React's HTMLAttributes
    slot_name?: string;
  }
}

interface Props {
  requestData: any
}


const HYModalCom = forwardRef(function (props: Props, ref: Ref<any>) {
  //  抛出绑定在改组件的一些方法 外面通过ref拿
  useImperativeHandle(ref, () => ({
    isShowModal: addModal,
    isEdit: isEdit
  }));
  // data
  const formLayout = {
    labelCol: { span: 7 },
    wrapperCol: { span: 17 },
  };
  const formItem = [
    {
      type: "Input",
      label: "邮箱",
      name: "username",
      required: true,
      style: { width: "250px" },
      placeholder: "请输入邮箱",
      rules: [
        () => ({
          validator(rule: any, value: any) {
            if (value && validateEmail(value)) {
              return Promise.reject("请输入正确邮箱！");
            }
            return Promise.resolve();
          },
        }),
      ],
    },
    {
      type: "Input",
      label: "真实名称",
      name: "truename",
      required: true,
      style: { width: "250px" },
      placeholder: "请输入姓名",
    },
    {
      type: "Input",
      label: "密码",
      name: "password",
      required: true,
      style: { width: "250px" },
      placeholder: "请输入密码",
    },
    {
      type: "Input",
      label: "手机号",
      name: "phone",
      required: true,
      style: { width: "250px" },
      placeholder: "请填写手机号",
      rules: [
        () => ({
          validator(rule: any, value: any) {
            if (value && validatePhone(value)) {
              return Promise.reject("请输入正确手机号码！");
            }
            return Promise.resolve();
          },
        }),
      ],
    },
    {
      type: "Select",
      label: "禁启用",
      options: "status",
      style: { width: "250px" },
      name: "status",
      required: true,
    },
    {
      type: "Slot",
      label: "权限",
      name: "role",
      slotName: "role",
      style: { width: "250px" },
    },
    {
      type: "Slot",
      label: "菜单权限",
      name: "role_menu",
      slotName: "role_menu",
      style: { width: "250px" },
    },
  ];
  const editData = {};
  const initialValues = {};
  //  const options=[]
  // 菜单权限
  const role_menu = [
    {
      // 一级
      label: "用户管理",
      value: "/user",
      // 子级
      child_item: [
        { label: "用户列表", value: "/user/list" },
        { label: "用户添加", value: "/user/add" },
      ],
    },
    {
      // 一级
      label: "部门管理",
      value: "/department",
      // 子级
      child_item: [
        { label: "部门列表", value: "/department/list" },
        { label: "添加部门", value: "/department/add" },
      ],
    },
  ];
  //hooks-data
  const formRef: any = useRef(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [options, setOptions] = useState([]);
  const [getPermVal, setgetPermVal] = useState<any[]>()
  const [id, setId] = useState()
  // redux 
  const redux_role_menu = useSelector((state: any) => (state.getIn(['user', 'role_menu'])), shallowEqual)
  const dispatch = useDispatch()

  const getRole = async () => {
    //从服务器获得的角色分配权限
    const res: any = await GetRole();
    res.data && setOptions(res.data);
  };
  const isEdit = (params: any) => {
    const getPermVal = params.role ? params.role.split(',') : []
    setId(params.id)
    setgetPermVal(getPermVal)
    // 有个bug第一次的时候-渲染不了 可能是因为里面实例还没生成
    params.status = params.status + '' //这里面设置的是字符串 所以需要处理一下 
    isShowModal();
    const refs: any = formRef.current
    refs && refs.formRef && refs.formRef.current.setFieldsValue(params)
  };
  const addModal = () => {
    setId(undefined)
    setgetPermVal([])
    // 关闭蒙层 --将redux里面的数据置空 
    dispatch(setRoleMenu({}))
    formRef.current.formRef.current.resetFields()
    isShowModal();
  }
  const isShowModal = (isFlag = true) => {
    setIsModalVisible(isFlag);
  };
  const getPerm = useCallback(
    (value: React.SetStateAction<CheckboxValueType[] | undefined>) => {
      setgetPermVal(value)
    },
    [setgetPermVal],
  );

  const handleCancel = () => {
    setId(undefined)
    setgetPermVal([])
    // 关闭蒙层 --将redux里面的数据置空 
    dispatch(setRoleMenu({}))
    isShowModal(false)
  };
  const handleOk = () => {
    formRef.current.onFinish()
  };
  const onFinish = async (val: any, formRef: any) => {
    try {
      const requestData = await formRef.validateFields();
      if (!requestData) return;
      if (id) {
        requestData["id"] = id;
      }

      // 处理密码--解密 CryptoJs.MD5 处理
      // 添加角色分配 
      const getPermVals = getPermVal as any
      const role = getPermVals.length > 0 ? getPermVals.join(',') : false;
      requestData['role'] = role;
      // 添加菜单权限分配 
      const role_menu = redux_role_menu
      let roleStr = ''
      for (const key in role_menu) {
        if (Object.hasOwnProperty.call(role_menu, key)) {
          const element = role_menu[key];
          for (const itm in element) {
            if (Object.hasOwnProperty.call(element, itm)) {
              roleStr = roleStr.concat(itm, ',')
            }
          }
        }
      }
      roleStr = roleStr.length > 0 ? roleStr.substring(0, roleStr.length - 1) : '';
      requestData['role_menu'] = roleStr
      const res: any = await custom({
        url: `${!id ? "/user/add/" : "/user/edit/"}`,
        data: requestData,
      });
      message.success(res.message);
      handleCancel();
      formRef.resetFields();
      //  刷新页面
      props.requestData();
    } catch (error) {
      console.log(error);
    }
  };
  // 生命周期
  useEffect(() => {
    getRole();
  }, []);
  return (
    <Modal
      title="Basic Modal"
      visible={isModalVisible}
      onOk={handleOk}
      onCancel={handleCancel}
    //   footer={null}
    >
      <HYFormCom
        formItem={formItem}
        formLayout={formLayout}
        submit={onFinish}
        editData={editData}
        initialValues={initialValues}
        isShowBtn={false}
        ref={formRef}
      >
        <div slot_name="role">
          <Checkbox.Group
            options={options}
            onChange={getPerm}
            value={getPermVal}
          />
        </div>
        <div slot_name="role_menu">
          {role_menu.map((item, index) => (
            <CheckBoxAll roleData={item} key={index} />
          ))}
        </div>
      </HYFormCom>
    </Modal>
  );
});

export default memo(HYModalCom);
